import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import MenuAPI, { RouteVO } from "@/api/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([]);
  /** 混合模式左侧菜单 */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);

  //组装数据
  const getData = (data: any) => {
    data.forEach((item: any) => {
      item.meta = {
        alwaysShow: item.always_show == 1 ? true : false,
        title: item.route_name,
        icon: item.icon,
        hidden: item.visible == 0 ? true : false,
        keepAlive: item.keep_alive == 1 ? true : false,
        params: null,
      };

      item.path = item.route_path;

      if (item.children && item.children.length > 0) {
        getData(item.children);
      } else {
        delete item.children;
      }
    });
    return data;
  };

  function filterTree(tree: any) {
    return tree
      .filter((node: any) => node.type !== 4) // 过滤掉 type 为 '4de' 的节点
      .map((node: any) => {
        // 如果有子节点，递归过滤
        if (node.children && node.children.length > 0) {
          return {
            ...node,
            children: filterTree(node.children), // 递归处理子节点
          };
        }
        return node; // 返回不含子节点的节点
      });
  }

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      MenuAPI.getRoutes()
        .then((data) => {
          let datas = [
            {
              path: "/system",
              component: "Layout",
              redirect: "/system/user",
              name: "/system",
              meta: {
                title: "系统管理",
                icon: "system",
                hidden: false,
                alwaysShow: false,
                params: null,
              },
              children: [
                {
                  path: "user",
                  component: "system/user/index",
                  name: "User",
                  meta: {
                    title: "用户管理",
                    icon: "el-icon-User",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "role",
                  component: "system/role/index",
                  name: "Role",
                  meta: {
                    title: "角色管理",
                    icon: "role",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "menu",
                  component: "system/menu/index",
                  name: "Menu",
                  meta: {
                    title: "菜单管理",
                    icon: "menu",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "dept",
                  component: "system/dept/index",
                  name: "Dept",
                  meta: {
                    title: "部门管理",
                    icon: "tree",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "dict",
                  component: "system/dict/index",
                  name: "Dict",
                  meta: {
                    title: "字典管理",
                    icon: "dict",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "log",
                  component: "system/log/index",
                  name: "Log",
                  meta: {
                    title: "系统日志",
                    icon: "document",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "dict-data",
                  component: "system/dict/data",
                  name: "DictData",
                  meta: {
                    title: "字典数据",
                    icon: "",
                    hidden: true,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "config",
                  component: "system/config/index",
                  name: "Config",
                  meta: {
                    title: "系统配置",
                    icon: "setting",
                    hidden: false,
                    keepAlive: true,
                    alwaysShow: false,
                    params: null,
                  },
                },
                {
                  path: "notice",
                  component: "system/notice/index",
                  name: "Notice",
                  meta: {
                    title: "通知公告",
                    icon: "",
                    hidden: false,
                    alwaysShow: false,
                    params: null,
                  },
                },
              ],
            },
            {
              path: "/demo",
              component: "Layout",
              redirect: "/demo/dict",
              name: "/demo",
              meta: {
                title: "系统",
                icon: "system",
                hidden: false,
                alwaysShow: false,
                params: null,
              },
              children: [
                {
                  path: "dict",
                  component: "demo/dict",
                  name: "Dict",
                  meta: {
                    title: "字典",
                    icon: "system",
                    hidden: false,
                    alwaysShow: false,
                    params: null,
                  },
                },
              ],
            },
          ];

          const dynamicRoutes = transformRoutes(getData(filterTree(data)));
          // const dynamicRoutes = transformRoutes(datas);
          routes.value = constantRoutes.concat(dynamicRoutes);
          resolve(dynamicRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: RouteVO[]) => {
  const asyncRoutes: RouteRecordRaw[] = [];

  routes.forEach((route) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules[`../../views/error-page/404.vue`];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route.children);
    }
    // console.log(tmpRoute);
    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例
 * @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
